package com.youtui.manager.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youtui.common.constant.ResultMessage;
import com.youtui.common.constant.SystemConstant;
import com.youtui.common.service.base.impl.BaseServiceImpl;
import com.youtui.common.util.NextIdUtil;
import com.youtui.common.util.ResultUtil;
import com.youtui.manager.mapper.AccountMapper;
import com.youtui.manager.model.Account;
import com.youtui.manager.model.AccountExample;
import com.youtui.manager.model.AccountExample.Criteria;
import com.youtui.manager.service.IAccountService;
import com.youtui.manager.service.IWithdrawalService;

@Service
public class AccountServiceImpl extends BaseServiceImpl implements IAccountService {

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private IWithdrawalService withdrawalService;

	@Override
	public Account findAccountByDevId(long devId) {

		AccountExample example = new AccountExample();
		Criteria criteria = example.createCriteria();
		criteria.andDevIdEqualTo(devId);
		List<Account> list = accountMapper.selectByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Integer updateAvailWallet(Long id, BigDecimal availWallet) {

		if (id == null || availWallet == null) {
			return ResultUtil.code_fail;
		}
		Account account = accountMapper.selectByPrimaryKey(id);
		if (account == null) {
			return ResultUtil.code_fail;
		}
		account.setAvailWallet(account.getAvailWallet().add(availWallet));
		account.setTotalWallet(account.getTotalWallet().add(availWallet));
		accountMapper.updateByPrimaryKeySelective(account);
		return ResultUtil.code_success;
	}

	@Override
	public Account add(Long devId) {

		Account account = new Account();
		account.setId(NextIdUtil.getNextId());
		account.setDevId(devId);
		account.setAvailWallet(new BigDecimal(0));
		account.setTotalWallet(new BigDecimal(0));
		account.setStatus(SystemConstant.status_effect);

		accountMapper.insert(account);
		return account;
	}

	@Override
	public ResultMessage updateWithdrawal(Long devId, BigDecimal applyMoney) {

		if (devId == null || applyMoney == null || applyMoney.doubleValue() <= 0) {
			return ResultUtil.result(ResultUtil.code_fail, "请求参数错误");
		}

		Account account = findAccountByDevId(devId);

		if (account == null) {
			return ResultUtil.result(ResultUtil.code_fail, "账户信息不存在");
		}

		if (account.getAvailWallet().doubleValue() < applyMoney.doubleValue()) {
			return ResultUtil.result(ResultUtil.code_fail, "账户余额不足");
		}

		withdrawalService.add(account, applyMoney);

		account.setAvailWallet(account.getAvailWallet().subtract(applyMoney));
		accountMapper.updateByPrimaryKeySelective(account);

		return ResultUtil.result(ResultUtil.code_success, "您发起提现申请，请等待审核");

	}
}
